<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {getChatData} from '@/api/common';
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    action:{
      type:String,
      require:true
    }
  },
  data() {
    return {
      chart: null,
    }
  },
  watch: {
    /*
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }*/
  },
  created(){
    getChatData(this.action).then(data=>{
      this.$nextTick(() => {
        this.initChart(data);
      })
    });
  },
  mounted() {

  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(chartData) {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(chartData)
    },
    setOptions(chartData) {
      let series = [];
      let legendData = [];
      chartData.data.forEach(item=>{
        legendData.push(item.legend);
        let colmunData = [];
        for (let k in item.data){
          colmunData.push(item.data[k]);
        };
        let data = {
          name : item.legend,
          smooth: true,
          type: 'line',
          data: colmunData,
          animationDuration: 2800,
          animationEasing: 'cubicInOut',
          itemStyle : {
            normal: {
              color: item.lineColor,
              lineStyle: {
                color: item.lineColor,
                width: 2
              },
              areaStyle: item.areaColor ? {color: item.areaColor} : ''
            }
          }
        };
        series.push(data);
      })
      this.chart.setOption({
        xAxis: {
          data: chartData.column,
          boundaryGap: false,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
          data:legendData
        },
        series: series
      })
    }
  }
}
</script>
